#include <stdio.h>

#include "xparameters.h"
#include "XSpips.h"
#include "Xil_types.h"
#include "xuartps_hw.h"

#include "netif/xadapter.h"
#include "xgpio_l.h"

#include "platform.h"
//#include "platform_config.h"
#if defined (__arm__) || defined(__aarch64__)
#include "xil_printf.h"
#endif

#include "lwip/tcp.h"
#include "xil_cache.h"

#if LWIP_DHCP==1
#include "lwip/dhcp.h"
#endif

/* defined by each RAW mode application */
void print_app_header();
int start_application();
int transfer_data();
void tcp_fasttmr(void);
void tcp_slowtmr(void);

/* missing declaration in lwIP */
void lwip_init();

extern void delay_SL(u32 delayCount);

#if LWIP_DHCP==1
extern volatile int dhcp_timoutcntr;
err_t dhcp_start(struct netif *netif);
#endif

extern volatile int TcpFastTmrFlag;
extern volatile int TcpSlowTmrFlag;
static struct netif server_netif;
struct netif *echo_netif;
struct tcp_pcb *pcb;


void
print_ip(char *msg, struct ip_addr *ip)
{
	print(msg);
	xil_printf("%d.%d.%d.%d\n\r", ip4_addr1(ip), ip4_addr2(ip),
			ip4_addr3(ip), ip4_addr4(ip));
}

void
print_ip_settings(struct ip_addr *ip, struct ip_addr *mask, struct ip_addr *gw)
{

	print_ip("Board IP: ", ip);
	print_ip("Netmask : ", mask);
	print_ip("Gateway : ", gw);
}

#if defined (__arm__) || defined(__aarch64__)
#if XPAR_GIGE_PCS_PMA_SGMII_CORE_PRESENT == 1 || XPAR_GIGE_PCS_PMA_1000BASEX_CORE_PRESENT == 1
int ProgramSi5324(void);
int ProgramSfpPhy(void);
#endif
#endif

#define TIMEOUT_HANDLER	(retVal=XST_FAILURE);
#define NREAD	(0x60)
#define NWRITE	(0x61)

#define SIO (0xF0)
#define STS (0xFE)
#define SPG (0xFF)

#define SPIF	(0x80)
#define RACK	(0x20)
#define RXRDY	(0x02)
#define TXRDY	(0x01)


extern int InitSPIDevice(XSpiPs *Spi_ptr,u16 DeviceId);
extern int writeBCM5396(XSpiPs *Spi_ptr, u8 page, u8 offset, u8 *pBuffer );

int writeBCM5396Reg( XSpiPs *Spi_ptr,u8 page, u8 offset, u8 *pBuffer ,u8 regType)
{
	u8 data[20],recvBuf[10];
	s32 retVal;
	u32 u32SendNum, u32ReqRetNum;

	int i;

	memset(recvBuf,0,10);
	for(i=0;i<20;i++)
		data[i]=i;
	// Set Page
	data[0] = NWRITE;
	data[1] = SPG;
	data[2] = page;
	u32SendNum = 3;
	u32ReqRetNum = 0;

	retVal = XSpiPs_PolledTransfer(Spi_ptr,data,NULL,u32SendNum);//pBuffer
	if( retVal != XST_SUCCESS )
	{
		printf("Call XSpiPs_PT_SL 1 Failed\n\r");
	}

	// Read STS
READ_STS_1:
	data[0] = NREAD;
	data[1] = STS;
	u32SendNum = 2;
	u32ReqRetNum = 1;
	retVal = XSpiPs_PolledTransfer(Spi_ptr,data,recvBuf,u32SendNum+u32ReqRetNum);
	/*
	xil_printf("STS 1 [%d]\n\r", retVal );
	for( u8Idx=0; u8Idx<u32ReqRetNum; u8Idx++ )
		xil_printf("%02x ", workBuf[u8Idx] );
	xil_printf("\n\r");
*/
	//
	if( retVal == XST_SUCCESS )
	{
		if((recvBuf[2] & SPIF)==0)//( workBuf[2] & SPIF )
		{
			// Set Page
			data[0] = NWRITE;
			data[1] = SPG;
			data[2] = page;
			u32SendNum = 3;
			u32ReqRetNum = 0;
			retVal = XSpiPs_PolledTransfer(Spi_ptr,data,NULL,u32SendNum+u32ReqRetNum);
			if( retVal != XST_SUCCESS )
			{
				printf("Call XSpiPs_PT_SL 1 Failed\n\r");
			}

			// Write Data
			data[0] = NWRITE;
			data[1] = offset;
			for(i=0;i<regType/8;i++)
			{
				data[2+i] = pBuffer[i];
			}
			u32SendNum = 2+(regType/8);
			u32ReqRetNum = 0;

			retVal = XSpiPs_PolledTransfer(Spi_ptr,data,NULL,u32SendNum+u32ReqRetNum);
			if( retVal != XST_SUCCESS )
			{
				printf("Call XSpiPs_PT_SL 2 Failed\n\r");
			}

		}
		else
		{
			//TIMEOUT_HANDLER;
			printf( "Timeout 1 Occured!\n\r" );
			delay_SL(0x100000);

			// Set Page
			data[0] = NWRITE;
			data[1] = SPG;
			data[2] = page;
			u32SendNum = 3;
			u32ReqRetNum = 0;
			//retVal = XSpiPs_PT_SL(Spi_ptr , data, pBuffer, u32SendNum, &u32ReqRetNum );
			retVal = XSpiPs_PolledTransfer(Spi_ptr,data,pBuffer,u32SendNum+u32ReqRetNum);
			if( retVal != XST_SUCCESS )
			{
				printf("Call XSpiPs_PT_SL 1 Failed\n\r");
			}

			goto READ_STS_1;
		}
	}
	else
		printf("Call XSpiPs_PT_SL 4 Failed\n\r");

	return retVal;
}
int test_lwip()
{

	int Status,k;
	u8 workBuf[10];

	u8 FiberworkBuf[10];

	u8 i;
	XSpiPs Spi;
	u32 _regData;
	u8 _recvData;


	Status = InitSPIDevice(&Spi,XPAR_PS7_SPI_0_DEVICE_ID);
	if (Status == 0)
	{
		xil_printf("InitSPIDevice PASSED\r\n");
	}
	else
	{
		xil_printf("InitSPIDevice FAILED\r\n");
	}
	/////////////////////write spi reg of 5396
	/*
	for(i=0;i<10;i++)
	  workBuf[i]=0xf0;
*/
	workBuf[0]=0xe0;
	workBuf[1]=0x1;
	workBuf[2]=0x0;

	FiberworkBuf[0]=0xe1;
	FiberworkBuf[1]=0x1;
	FiberworkBuf[2]=0x0;
//	Status = writeBCM5396(&Spi, 0x10, 0x20, workBuf );
	for(i=0x10;i<=0x1f;i++)
	{
		if((i!=0x12)&&(i!=0x13))
		{
			Status = writeBCM5396(&Spi, i, 0x20, workBuf );
		}
	}

	Status = writeBCM5396(&Spi, 0x12, 0x20, FiberworkBuf );
	Status = writeBCM5396(&Spi, 0x13, 0x20, FiberworkBuf );

	u8 buf[10];

	buf[0]=0xfd;
	buf[1]=0xff;
	buf[2]=0x01;
	writeBCM5396Reg(&Spi, 0x31, 0x00, buf,32);//Port 0

	buf[0]=0xfe;
	buf[1]=0xff;
	buf[2]=0x01;
	writeBCM5396Reg(&Spi, 0x31, 0x04, buf,32);//Port 1

	xil_printf("Set bcm5396 Finish break loop done\r\n");


	XGpio_WriteReg(0x80000000,0x1000,0xa5a5);

	XGpio_WriteReg(0x80000000,0x1004,0x70);

//  initial uart

	_regData = XUartPs_ReadReg(XPAR_XUARTPS_0_BASEADDR, XUARTPS_CR_OFFSET);

		/*
		 * Enable TX and RX for the device
		 */
	XUartPs_WriteReg(XPAR_XUARTPS_0_BASEADDR, XUARTPS_CR_OFFSET,
			  ((_regData & ~XUARTPS_CR_EN_DIS_MASK) | XUARTPS_CR_TX_EN | XUARTPS_CR_RX_EN));


#if __aarch64__
	Xil_DCacheDisable();
#endif


#if 1

	struct ip_addr ipaddr, netmask, gw;

	/* the mac address of the board. this should be unique per board */
	unsigned char mac_ethernet_address[] =
	{ 0x00, 0x0a, 0x35, 0x00, 0x01, 0x02 };

	echo_netif = &server_netif;

#if defined (__arm__) || defined(__aarch64__)
#if XPAR_GIGE_PCS_PMA_SGMII_CORE_PRESENT == 1 || XPAR_GIGE_PCS_PMA_1000BASEX_CORE_PRESENT == 1
	ProgramSi5324();
	ProgramSfpPhy();
#endif
#endif

	init_platform();

#if LWIP_DHCP==1
    ipaddr.addr = 0;
	gw.addr = 0;
	netmask.addr = 0;
#else
	/* initliaze IP addresses to be used */
	IP4_ADDR(&ipaddr,  192, 168,   1, 10);
	IP4_ADDR(&netmask, 255, 255, 255,  0);
	IP4_ADDR(&gw,      192, 168,   1,  1);
#endif
	print_app_header();

	lwip_init();

  	/* Add network interface to the netif_list, and set it as default */
	if (!xemac_add(echo_netif, &ipaddr, &netmask,
						&gw, mac_ethernet_address,
						PLATFORM_EMAC_BASEADDR)) {
		xil_printf("Error adding N/W interface\n\r");
		return -1;
	}


	netif_set_default(echo_netif);


	/* now enable interrupts */
	platform_enable_interrupts();


	/* specify that the network if is up */
	netif_set_up(echo_netif);


#if (LWIP_DHCP==1)
	/* Create a new DHCP client for this interface.
	 * Note: you must call dhcp_fine_tmr() and dhcp_coarse_tmr() at
	 * the predefined regular intervals after starting the client.
	 */
	dhcp_start(echo_netif);
	dhcp_timoutcntr = 24;

	while(((echo_netif->ip_addr.addr) == 0) && (dhcp_timoutcntr > 0))
		xemacif_input(echo_netif);


	if (dhcp_timoutcntr <= 0) {
		if ((echo_netif->ip_addr.addr) == 0) {
			xil_printf("DHCP Timeout\r\n");
			xil_printf("Configuring default IP of 192.168.100.10\r\n");
			IP4_ADDR(&(echo_netif->ip_addr),  192, 168,   100, 10);
			IP4_ADDR(&(echo_netif->netmask), 255, 255, 255,  0);
			IP4_ADDR(&(echo_netif->gw),      192, 168,   100,  1);
		}
	}

	ipaddr.addr = echo_netif->ip_addr.addr;
	gw.addr = echo_netif->gw.addr;
	netmask.addr = echo_netif->netmask.addr;
#endif

	print_ip_settings(&ipaddr, &netmask, &gw);

	/* start the application (web server, rxtest, txtest, etc..) */
	pcb = start_application();

//	xil_printf("Finish Configuring zynq IP of 192.168.1.10\r\n");

	return 0;


	/* receive and process packets */
	while (1) {
		if (TcpFastTmrFlag) {
			tcp_fasttmr();
			TcpFastTmrFlag = 0;
		}
		if (TcpSlowTmrFlag) {
			tcp_slowtmr();
			TcpSlowTmrFlag = 0;
		}

	//	_recvData = XUartPs_RecvByte(XPAR_XUARTPS_0_BASEADDR);

		_recvData = XUartPs_ReadReg(XPAR_XUARTPS_0_BASEADDR, XUARTPS_FIFO_OFFSET);
		if (_recvData == 'e'|| _recvData == 'E')
		{
			xil_printf("test lwip exit!\r\n");

		/*	netif_remove(echo_netif);

			if(tcp_close(pcb) == 0)
			{
				xil_printf("tcp close!\r\n");
			}

			cleanup_platform();*/

			return 0;
		}
		xemacif_input(echo_netif);
		transfer_data();
	}

	/* never reached */
	cleanup_platform();
#endif

	return 0;
}


